import { useState } from 'react';
import { LockOutlined } from "@ant-design/icons";
import { Input } from "antd";

export default function PasswordInput({onChange, ...props}) {

    const [level, setLevel] = useState(0);
    const warnings = [
        {color: 'red', progress: 10, text: '较弱'},
        {color: 'orange', progress: 50, text: '中等'},
        {color: 'green', progress: 100, text: '较强'},
    ];
    const handleChange = (e) => {
        let currentLevel = 0;
        const password = e.target.value;
        if(password.length > 4) {
            const regexs = [/\d/, /[a-z]/, /[A-Z]/];
            const matched = regexs.filter((regex) => password.match(regex)).length;
            if(matched > 0) {
                currentLevel += matched - 1;
            }
            if(`${password}`.replace(/\w+/g, '').length) {
                currentLevel ++;
            }
            if(currentLevel > 2) {
                currentLevel = 2;
            }
        }
        setLevel(currentLevel);
        if(onChange) {
            onChange(e);
        }
    }

    const warn = warnings[level || 0];
    return <>
        <Input.Password {...props} size='large' onChange={handleChange} prefix={<LockOutlined />} />
        <div className='mt-2 flex gap-4 items-center'>
            <div className='flex-1 rounded h-2 bg-gray-200'>
                <div className='h-2 rounded' style={{width: `${warn.progress}%`, backgroundColor: warn.color}}></div>
            </div>
            <div>{warn.text}</div>
        </div>
        <div className='flex flex-col gap-2 my-2 text-gray-400'>
            <span>1. 密码大于4位数开始计算强度等级。</span>
            <span>2. 数字、标点符号、小写英文字母，大写英文字母，均会让密码等级提升1级。</span>
        </div>
    </>;
}
